package org.abettor.pushbox.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.db.PushBoxDbHelper;
import org.abettor.pushbox.db.PushBoxMapBeanManage;
import org.abettor.pushbox.map.Boxmap;
import org.abettor.pushbox.map.BoxmapUtil;
import org.abettor.pushbox.model.PushBoxMapBean;
import org.abettor.pushbox.util.Md5Util;
import org.abettor.pushbox.view.MakeMapView;
import org.abettor.pushbox.view.PushBoxButton;
import org.abettor.pushbox.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 * 制作地图的activity
 * 
 * @author jzh
 * 
 */
public class MakeMapActivity extends Activity {
	private int selfmap_id = -1;// 自做地图的id
	//private final int PANNELHEIGHT = 100;// 下边按钮的高度
	@SuppressWarnings("unused")
	private LinearLayout m_drawmap_layout;// 画图的layout
	private PushBoxButton m_boxbutton, m_wallbutton, m_destbutton,
			m_personbutton, m_cancelbutton;// 箱子的按钮
	private final int BOX_PRESSED = 0, WALL_PRESSED = 1, DEST_PRESSED = 2,
			CANCEL_PRESSED = 3, PERSON_PRESSED = 4;
	private int button_status = -1;// 按钮的状态
	private int width = 10, height = 10;// 地图的宽度和高度
	private Handler mHandler = new Handler();
	private MakeMapView makeMapView = null;// 画图的控件
	private final int FINISH_MAP = Menu.FIRST;// 结束作图
	private final int SAVE_DRAFT = Menu.FIRST + 1;// 保存草稿
	private final int ZOOM_IN = Menu.FIRST + 2;
	private final int ZOOM_OUT = Menu.FIRST + 3;
	private final int DEL_DRAFT = Menu.FIRST + 4;
	PushBoxMapBeanManage manage = null;

	// 按钮的监听器
	private class ButtonOnTouchListener implements OnTouchListener {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				if (v == m_boxbutton) {
					button_status = BOX_PRESSED;
					makeMapView.setStatus(MakeMapView.BOX_PRESSED);
					resetButtonStatus();
				} else if (v == m_wallbutton) {
					makeMapView.setStatus(MakeMapView.WALL_PRESSED);
					button_status = WALL_PRESSED;
					resetButtonStatus();
				} else if (v == m_destbutton) {
					makeMapView.setStatus(MakeMapView.DEST_PRESSED);
					button_status = DEST_PRESSED;
					resetButtonStatus();
				} else if (v == m_cancelbutton) {
					makeMapView.setStatus(MakeMapView.CANCEL_PRESSED);
					button_status = CANCEL_PRESSED;
					resetButtonStatus();
				} else if (v == m_personbutton) {
					makeMapView.setStatus(MakeMapView.PERSON_PRESSED);
					button_status = PERSON_PRESSED;
					resetButtonStatus();
				}
			}
			return true;
		}
	}

	// 设置按钮的状态
	private void resetButtonStatus() {
		m_boxbutton.setPressed(false);
		m_wallbutton.setPressed(false);
		m_destbutton.setPressed(false);
		m_cancelbutton.setPressed(false);
		m_personbutton.setPressed(false);
		switch (button_status) {
		case BOX_PRESSED:
			m_boxbutton.setPressed(true);
			break;
		case WALL_PRESSED:
			m_wallbutton.setPressed(true);
			break;
		case DEST_PRESSED:
			m_destbutton.setPressed(true);
			break;
		case CANCEL_PRESSED:
			m_cancelbutton.setPressed(true);
			break;
		case PERSON_PRESSED:
			m_personbutton.setPressed(true);
			break;
		}
		m_boxbutton.invalidate();
		m_wallbutton.invalidate();
		m_destbutton.invalidate();
		m_cancelbutton.invalidate();
		m_personbutton.invalidate();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.make_map_activity);
		makeMapView = (MakeMapView) findViewById(R.id.boxview);
		makeMapView.setLongClickable(true);
		makeMapView.setFocusable(true);
		m_boxbutton = (PushBoxButton) findViewById(R.id.box_id);
		m_boxbutton.setOnTouchListener(new ButtonOnTouchListener());
		m_wallbutton = (PushBoxButton) findViewById(R.id.wall_id);
		m_wallbutton.setOnTouchListener(new ButtonOnTouchListener());
		m_destbutton = (PushBoxButton) findViewById(R.id.dest_id);
		m_destbutton.setOnTouchListener(new ButtonOnTouchListener());
		m_cancelbutton = (PushBoxButton) findViewById(R.id.cancel_id);
		m_cancelbutton.setOnTouchListener(new ButtonOnTouchListener());
		m_personbutton = (PushBoxButton) findViewById(R.id.person_id);
		m_personbutton.setOnTouchListener(new ButtonOnTouchListener());
		m_drawmap_layout = (LinearLayout) findViewById(R.id.draw_map_layout);
		//resetLayOut();
		// 初始化地图
		Boxmap map = initTheMap();
		if (map != null) {
			this.makeMapView.setMap(map);// 编辑地图
			generateImage();
		} else {
			alertDialog(this.getText(R.string.make_map_dialog_title), width
					+ "", height + "");// 新创建地图
		}
		manage = new PushBoxMapBeanManage(this);

		//	设置墙为默认选中
		makeMapView.setStatus(MakeMapView.WALL_PRESSED);
		button_status = WALL_PRESSED;
		resetButtonStatus();
	}

	// 初始化地图
	private Boxmap initTheMap() {
		Intent intent = getIntent();
		Boxmap map = null;
		Bundle extras = intent.getExtras();
		if (extras == null) {
			return null;
		}
		selfmap_id = extras.getInt("_id");// 获得数据的id
		PushBoxDbHelper helper = new PushBoxDbHelper(this);
		SQLiteDatabase base = helper.getWritableDatabase();
		Cursor c = base.query(PushBoxDbHelper.PUSH_BOX_TABLE_NAME,
				new String[] { PushBoxDbHelper.PUSH_BOX_MAP_FILENAME },
				PushBoxDbHelper.PUSH_BOX_ID + "=" + selfmap_id, null, null,
				null, null);
		if (c.moveToFirst()) {
			int index = c.getColumnIndex(PushBoxDbHelper.PUSH_BOX_MAP_FILENAME);
			String name = c.getString(index);// 获得名字
			byte[] buf = null;
			try {
				buf = readFile(name);
			} catch (IOException e) {
			}
			map = BoxmapUtil.paraArrayToMap(buf);// 生成地图
		}
		c.close();
		base.close();
		return map;
	}

	// 读取地图文件
	private byte[] readFile(String mapFileName) throws IOException {
		String filepath = Config.getSelfBasePath() + File.separator
				+ mapFileName + ".map";
		return readFileByPath(filepath);
	}

	private byte[] readFileByPath(String filename) throws IOException {
		File file = new File(filename);
		if (!file.exists()) {
			return null;
		}
		InputStream in = new FileInputStream(file);
		ByteArrayOutputStream byteout = new ByteArrayOutputStream();
		int value = 0;
		while ((value = in.read()) != -1) {
			byteout.write(value);
		}
		return byteout.toByteArray();
	}

	// 产生图片
	private void generateImage() {
		makeMapView.generateBitmap();
	}
	// 读取屏幕高度
	@SuppressWarnings("unused")
	private int readScreenHeight() {
		WindowManager manage = getWindowManager();
		Display display = manage.getDefaultDisplay();
		return display.getHeight();
	}

	// 弹出对话框的操作
	private void alertDialog(CharSequence str, CharSequence width,
			CharSequence height) {
		LayoutInflater inflater = MakeMapActivity.this.getLayoutInflater();
		final ViewGroup view = (ViewGroup) inflater.inflate(
				R.layout.make_map_dialog, null, false);
		EditText widthEdit = (EditText) view.findViewById(R.id.width);
		EditText heightEdit = (EditText) view.findViewById(R.id.height);
		widthEdit.getEditableText().clear();
		widthEdit.getEditableText().append(width);
		heightEdit.getEditableText().clear();
		heightEdit.getEditableText().append(height);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog dialog = builder.create();
		//拦截back key
		dialog.setOnKeyListener(new OnKeyListener(){
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if(keyCode == KeyEvent.KEYCODE_BACK){
					return true;
				}
				return false;
			}});
		dialog.setView(view);
		dialog.setTitle(str);
		dialog.setButton(DialogInterface.BUTTON_POSITIVE, this
				.getText(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						EditText widthEdit = (EditText) view
								.findViewById(R.id.width);
						EditText heightEdit = (EditText) view
								.findViewById(R.id.height);
						final Editable edit1 = widthEdit.getEditableText();
						final Editable edit2 = heightEdit.getEditableText();
						// 输入的宽高为空
						if (edit1.toString().equals("")
								|| edit2.toString().equals("")) {
							mHandler.post(new Runnable() {
								@Override
								public void run() {
									alertDialog(
											MakeMapActivity.this
													.getText(R.string.make_map_dialog_reset_message),
											edit1.toString(), edit2.toString());
								}
							});
							return;
						}
						// 输入的宽高小于5
						if (Integer.parseInt(edit1.toString()) < 5
								|| Integer.parseInt(edit2.toString()) < 5) {
							mHandler.post(new Runnable() {
								@Override
								public void run() {
									alertDialog(
											MakeMapActivity.this
													.getText(R.string.make_map_dialog_reset_message),
											edit1.toString(), edit2.toString());
								}
							});
							return;
						}
						MakeMapActivity.this.width = Integer.parseInt(edit1
								.toString());
						MakeMapActivity.this.height = Integer.parseInt(edit2
								.toString());
						Boxmap map = new Boxmap(MakeMapActivity.this.width,
								MakeMapActivity.this.height);
						makeMapView.setMap(map);
						generateImage();
					}
				});
		dialog.show();
	}

	/**
	 * 创建系统菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, FINISH_MAP, 0, R.string.finish_map)
				.setIcon(R.drawable.save);
		menu.add(0, SAVE_DRAFT, 1, R.string.save_draft).setIcon(
				R.drawable.draft);
		menu.add(0, ZOOM_IN, 2, R.string.zoom_in).setIcon(R.drawable.zoom_in);
		menu.add(0, ZOOM_OUT, 3, R.string.zoom_out)
				.setIcon(R.drawable.zoom_out);
		return result;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (this.selfmap_id == -1) {// 还没有保存草稿,不需要删除草稿的按钮
			menu.removeItem(DEL_DRAFT);
		} else {// 已经保存了草稿
			MenuItem item = menu.findItem(DEL_DRAFT);
			if (item == null) {
				menu.add(0, DEL_DRAFT, 4, R.string.del_draft).setIcon(
						R.drawable.remove);
			}
		}
		return super.onPrepareOptionsMenu(menu);
	}

	/**
	 * 系统菜单执行的操作
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case FINISH_MAP:
			finishMap();
			break;
		case SAVE_DRAFT:
			savedraft();
			break;
		case DEL_DRAFT:
			deleteDraft();
			break;
		case ZOOM_IN:
			zoomin();
			break;
		case ZOOM_OUT:
			zoomout();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private ProgressDialog dialog;// 进度条对话框

	// 放大地图的操作
	private void zoomin() {
		this.makeMapView.zoomIn();
	}

	// 删除草稿的操作
	private void deleteDraft() {
		if (this.selfmap_id == -1) {
			return;
		}
		String filename = manage.getFileName(selfmap_id);
		manage.delPushBoxMapBean(selfmap_id);
		deleteTheFile(filename);
		Toast.makeText(MakeMapActivity.this, R.string.del_draft_success,
				Toast.LENGTH_LONG).show();
		super.onBackPressed();
	}

	// 缩小地图的操作
	private void zoomout() {
		this.makeMapView.zoomOut();
	}

	// 完成设计地图的操作
	private void finishMap() {
		// 显示对话框进度条
		dialog = new ProgressDialog(MakeMapActivity.this);
		dialog.setTitle(R.string.check_map);
		dialog.setMessage(getText(R.string.checking));
		Thread thread = new Thread() {
			private boolean flag = false;

			@Override
			public void run() {
				int retVal = makeMapView.checkMapIsValid();
				if (retVal == Boxmap.MapCheckErrorCode.SUCCESS) {
					Boxmap map = makeMapView.getMap();
					map = Boxmap.optimization(map);
					makeMapView.setMap(map);
					saveMap(makeMapView.getMap(), 0);// 保存地图
					flag = true;
				}
				dialog.dismiss();
				final String msg = Boxmap.changeErrorCodeToStr(retVal);
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								MakeMapActivity.this);
						AlertDialog alert = builder.create();
						alert.setTitle(R.string.check_map);
						alert.setButton(DialogInterface.BUTTON_POSITIVE,
								MakeMapActivity.this
										.getText(android.R.string.ok),
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// 这里跳到展示自制地图的页面
										if (flag) {
											mHandler.post(new Runnable() {
												@Override
												public void run() {
													MakeMapActivity.this
															.finish();
												}
											});
										}
									}
								});
						alert.setMessage(msg);
						alert.show();
					}
				});
			}
		};
		// 保存地图
		thread.start();
		dialog.show();
	}

	// 保存地图的数据
	private void saveMap(Boxmap map, int isdraft) {
		byte[] array = BoxmapUtil.paraMapToArray(map, true);
		PushBoxMapBean bean = new PushBoxMapBean();
		String name = Md5Util.toMd5(array);
		bean.setType(PushBoxMapBean.SELFMAKE_TYPE);
		bean.setName(name);
		bean.setIsdraft(isdraft);
		bean.setId(selfmap_id);// 设置id
		bean.setMapFileName(name);
		// 获得修改前的文件名字
		String filename = manage.getFileName(selfmap_id);
		// 向数据库中添加记录
		selfmap_id = manage.insertOrUpdateBoxMapBean(bean);
		try {
			writeFile(array, name);
			// 把以前没用的文件删除掉
			if (!name.equals(filename))
				deleteTheFile(filename);
		} catch (Exception e) {
			throw new RuntimeException(e.fillInStackTrace());
		}
	}

	// 删除过期的不用的文件
	private void deleteTheFile(String filename) {
		try {
			File file = new File(Config.getSelfBasePath() + File.separator
					+ filename + ".map");
			if (file.exists()) {
				file.delete();
			}
			file = new File(Config.getSelfBasePath() + File.separator
					+ filename + ".thumb");
			if (file.exists()) {
				file.delete();
			}
			file = new File(Config.getSelfBasePath() + File.separator
					+ filename + ".draft");
			if (file.exists()) {
				file.delete();
			}
		} catch (Exception e) {
		}
	}

	// 保存文件
	private void writeFile(byte[] buf, String name)
			throws IOException {
		File file = null;
		file = new File(Config.getSelfBasePath() + File.separator + name
				+ ".map");
		FileOutputStream os = new FileOutputStream(file);
		os.write(buf);
		os.close();
	}

	// 保存草稿的操作
	private void savedraft() {
		saveMap(makeMapView.getMap(), 1);// 保存地图
		Toast.makeText(MakeMapActivity.this, R.string.save_draft_success,
				Toast.LENGTH_LONG).show();
		this.makeMapView.setHasModed(false);// 设置编辑位
	}

	private void back() {
		super.onBackPressed();
	}

	// 拦截回退的事件
	@Override
	public void onBackPressed() {
		if (makeMapView.isHasModed()) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					MakeMapActivity.this);
			AlertDialog alert = builder.create();
			alert.setTitle(R.string.save_draft);
			alert.setMessage(MakeMapActivity.this
					.getText(R.string.is_save_draft));
			alert.setButton(DialogInterface.BUTTON_POSITIVE, this
					.getText(android.R.string.ok),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							savedraft();// 保存草稿
						}
					});
			alert.setButton(DialogInterface.BUTTON_NEGATIVE, this
					.getText(android.R.string.cancel),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							back();
						}
					});
			alert.show();
		} else {
			super.onBackPressed();
		}
	}
}
